/**
 * Created by zhaoxk on 2016/12/9.
 */
import React from 'react';
import $ from 'jquery';
import {Button, message, Icon, Popover, Input, Tree} from 'antd';
import _ from 'lodash';
import {report, cates, types} from './reportData/data';
import CateBar from './cateBar';
import TypeBar from './typeBar';
import UploadImage from './uploadImg';
import Title from '../_/title';
import ReportForm from './reportForm';
import {context} from '../_';
import redux from '../_/redux';
import moment from 'moment';
import tinymce from '../../libs/tinymce';
//TODO data 临时数据
import {data} from './reportData';
import CompTree from './frame/componentsTree';
const loader = (...args) => {
    const {vInfoload, params} = args[0];
    if (typeof params !== "undefined") {
        vInfoload({Id: params.id});
    }
};
@context('params')
@redux('visitView', {
    prefix: "vInfo",
    loader,
    actions: ['load']
})
@redux('dict', {
    prefix: 'dict',
    actions: ['loadAll']
})
@redux('printTemplate', {
    prefix: 'printTemplate',
    loadArgs: {
        id: 1,
        _fs: '*'
    },
    actions: 'load'
})
@redux('medicalRecord', {
    prefix: 'classAndSegAll',
    actions: 'getClassAndSeg',
    loadArgs: {
        type: 1
    },
    loader: (props) => {
        props.classAndSegAllgetClassAndSeg();
    }
})

export default class WriteReport extends React.Component {
    state = {
        tree: this.props.classAndSegAlldata,
        form: []
    };

    componentDidMount() {
        const setSize = (h) => {
            //console.log('wrwrtewrdff', h);
        };
        this.props.setSize(h => {
            setSize(h);
        });
        $(window).resize(() => {
            this.props.setSize(h => {
                setSize(h);
            });
        });
    }

    componentWillUnmount() {
        //销毁组件时还需要把向下的空白边类加上
        const mainRight = $('#main-right');
        mainRight.addClass('padding-b');
    }

    addType = item => {
        const ELEMENTS = {
            PositionContent: '',
            Eyes: '',
            PastHistoryEyeContent: '',
            HappenTime: ''
        };
        const form = _.clone(this.state.form),
            _f = _.filter(form, f => {
                if (item.class_code === f.class_code) {
                    return f;
                }
            }),
            newForm = item => {
                if (_f.length < 1) {
                    //表单池里没有这个分类
                    const newClass = {
                        code: item.class_code,
                        segType: [
                            {
                                code: item.code,
                                data: [ELEMENTS]
                            }
                        ]
                    };
                    form.push(newClass);
                    return form;
                }
                //表单池里有这个分类
                const _t = _.filter(_f.segType, t => {
                    if (item.code === t.code) {
                        return t;
                    }
                });
                if (_t.length < 1) {
                    //分类中没有指定段落
                    if (!_f.segType) {
                        _f.segType = [];
                    }
                    _f.segType.push(
                        {
                            code: item.code,
                            data: [ELEMENTS]
                        }
                    );
                }
            };
    };

    render() {
        return (
            <div id="workBoard">
                <div id="topBar">
                    <div>工作台主要功能区，保存，选择模板等图形按钮区</div>
                </div>
                <div id="mainBar">
                    <div id="formArea">adfdfdadf</div>
                    <div id="moduleTree">
                        <CompTree
                            data={this.props.classAndSegAlldata}
                            addType={this.addType}
                        />
                    </div>
                    <div id="editIndex">editIndex</div>
                </div>
                <div id="bottomBar">
                    <div>版本选择，作者信息等...</div>
                </div>
            </div>
        );
    }
}
WriteReport.defaultProps = {
    setSize: (cb) => {
        const wrap = $('.layout-right:first');
        if (!wrap) return;
        const wrap_h = $(window).height() - 48,
            workBoard = $('#workBoard'),
            mainRight = $('#main-right'),
            topBar = $('#topBar'),
            tb_h = topBar.height(),
            bottomBar = $('#bottomBar'),
            bb_h = bottomBar.height(),
            mainBar = $('#mainBar'),
            formArea = $('#formArea'),
            moduleTree = $('#moduleTree'),
            mt_w = moduleTree.width(),
            editIndex = $('#editIndex'),
            ei_w = editIndex.width();
        wrap.css({
            overflow: 'hidden'
        });
        mainRight.removeClass('padding-b');
        workBoard.css({
            height: wrap_h + 'px',
            padding: `${tb_h}px 0 ${bb_h}px`,
        });
        mainBar.css({
            padding: `0 ${ei_w}px 0 ${mt_w}px`,
        });
        if (typeof cb === 'function') {
            cb(wrap_h - (tb_h + bb_h));
        }
    }
};
/*
 export default class WriteReport extends React.Component {
 static setSize = (cb) => {
 const wrap = document.getElementById('workspaceWrap');
 if (!wrap) return;
 const _r = window.innerHeight - 62;
 wrap.style.height = _r + 'px';
 if (typeof cb === 'function') {
 const _h = document.getElementById('_barMain').offsetHeight;
 cb(_h);
 }
 };
 /!**
 * 数组转对象
 * @param arr       Array  原数组
 * @param key       String 原数组中的元素必须是个对象，对象中包含key键
 * @param take      String 转换后仅保存的部分，对象中包含take键，否则保留整个对象
 * @returns {{}}    Object 返回以原数组每个元素key键的值为键的元素集合
 *!/
 static arr2ObjByKey = (arr, key, take) => {
 if (arr && Array.isArray(arr) && arr.length > 0) {
 const obj = {};
 for (let i = 0; i < arr.length; i++) {
 if (typeof arr[i] === 'object' && arr[i][key]) {
 if (!obj[arr[i][key]]) {
 obj[arr[i][key]] = [];
 }
 if (take && arr[i][take]) {
 obj[arr[i][key]] = arr[i][take];
 } else {
 obj[arr[i][key]].push(arr[i]);
 }
 }
 }
 return obj;
 }
 };

 constructor(props) {
 super(props);
 this.state = {
 cur: 0,
 report,
 addImgModal: {
 visible: false,
 confirmLoading: false
 }
 };
 this.reset = this.reset.bind(this);
 }

 componentWillMount() {
 const initialIndex = 0,
 form = WriteReport.arr2ObjByKey(report.items, 'type', 'data');
 this.reset(null, initialIndex, {reportF: form});
 loader(this.props);
 }

 componentDidMount() {
 tinymce.printCheck();
 const setheight = (h) => {
 this.setState({
 iHeight: h + 'px'
 });
 };
 WriteReport.setSize(setheight);
 window.onresize = () => {
 WriteReport.setSize(setheight);
 };

 //检索所有段落配置中的数据源获取方式
 const dataSources = _.reduce(types, (res, v) =>
 (_.reduce(v.renderData, (res, v2) => {
 if (v2.dataSource && v2.dataMethod !== 'ajax') {
 const keyName = `${v2.dataSource}`;
 const keys = res[keyName] = res[keyName] || (res[keyName] = {});
 //字典数据类型
 if (v2.dataArgs && v2.dataArgs.type) {
 v2.dataKey = `${v2.dataSource}.${v2.dataArgs.type}`;
 keys[v2.dataArgs.type] = v2.dataKey;
 }
 }
 return res;
 }, res))
 , {});
 if (this.props.dictloadAll && dataSources.dict) {
 this.props.dictloadAll(dataSources.dict, (types, data) => {
 /!*eslint no-console:0*!/
 console.log(types, data);
 });
 }
 }

 onPrintPreview = () => {
 const [obj = {}] = this.props.printTemplatedata;
 const vInfodata = this.props.vInfodata;
 const visitData = vInfodata && vInfodata.length ? vInfodata[0] : {};
 const patient = {
 ...visitData,
 Nation: '汉族',
 Gender: '男',
 Profession: '工程师',
 MaritalStatus: '未婚',
 VisitDate: new moment().format('YYYY-MM-DD HH:mm:ss')
 };
 const objNew = tinymce.printWrapper('#printWrapper', JSON.parse(obj.Content), {patient, visit: patient});
 tinymce.printInit(objNew, 'PREVIEW');
 }

 addType(typeId) {
 const curForm = _.clone(this.state.reportF),
 targetType = curForm[typeId];
 if (!targetType) {
 curForm[typeId] = [];
 }
 curForm[typeId].push({});
 this.setState({
 reportF: curForm
 });
 }

 //开启添加图片的对话框
 addImg = (type, typeId, i) => {
 const {visible, confirmLoading} = this.state.addImgModal;
 console.log(type, typeId, i);
 if (!visible) {
 this.setState({
 addImgModal: {
 visible: true,
 confirmLoading,
 current: {
 type,
 typeId,
 i
 }
 }
 });
 }
 };

 addImgOnOk = (v) => {
 const oldState = this.state.addImgModal,
 {current} = oldState,
 obj = {
 tid: current.typeId,
 i: current.i,
 name: 'attImg',
 value: v
 };
 this.updateValue(obj);
 };

 addImgOnCancel = () => {
 this.setState({
 addImgModal: {
 visible: false,
 confirmLoading: false,
 current: null
 }
 });
 console.log('oncancel');
 };

 toolEvent(type, typeId, i) {
 const curForm = _.clone(this.state.reportF),
 targetType = curForm[typeId];
 switch (type) {
 case 'remove':
 targetType[i] = null;
 break;
 case 'addRM':
 targetType[i].remark = '';
 break;
 case 'delRM':
 delete targetType[i].remark;
 break;
 case 'addImg':
 this.addImg(type, typeId, i);
 break;
 default:
 console.error('事件未定义：\n事件类型', type, '\n表单类型id', typeId, '\n序号', i);
 }
 this.setState({
 reportF: curForm
 });
 }

 updateValue(obj, type) {
 const curForm = _.clone(this.state.reportF);
 switch (type) {
 case 'push':
 const data = curForm[obj.tid][obj.i][obj.name];
 if (_.isArray(data)) {
 data.push(obj.value);
 console.log('curForm+++', curForm);
 } else {
 throw new Error('目标数据不是数组，不可以使用push类型的插入方式');
 }
 break;
 default:
 curForm[obj.tid][obj.i][obj.name] = obj.value;
 }
 this.setState({
 reportF: curForm
 }, () => {
 console.log('curForm', curForm);
 });
 }

 reset(id, i, add) {
 const type = WriteReport.arr2ObjByKey(types, 'cat'),
 title = cates[i].label,
 curCate = type[id || cates[i].id];
 let newState = {
 cur: i,
 title,
 curCate
 };
 if (add) {
 newState = {
 ...newState,
 ...add
 };
 }
 this.setState({
 ...newState
 });
 }

 changeCate(id, index) {
 this.reset(id, index);
 }

 need2save(yn) {
 this.setState({
 need2save: yn
 });
 }

 receiveData(res) {
 if (res.type === 'error') {
 const e = res.value,
 firstError = _.keys(e)[0];
 const ctn = firstError.split('_'),
 typeId = ctn[0],
 nameId = ctn[1],
 cateId = _.find(types, c => typeId === c.id).cat,
 cateIndex = _.findIndex(cates, c => c.id === cateId),
 cate = _.find(cates, c => cateId === c.id).label,
 type = _.find(types, c => typeId === c.id).label,
 name = _.find(_.find(types, c => typeId === c.id).renderData, rt => nameId === rt.name).label;
 message.error(`${cate}-${type}-${name}-有错误`);
 this.reset(cateId, cateIndex);
 } else {
 //TODO 提交病历表单数据 res.value，需要加上病例的其他数据一起提交
 console.log('需要提交病历表单数据', res.value);
 }
 this.need2save(false);
 }

 render() {
 const vInfodata = this.props.vInfodata;
 const {Name, Birthday, chargeType, Gender} = vInfodata && vInfodata.length ? vInfodata[0] : {},
 pGender = (g => {
 switch (g) {
 case '2':
 return '女';
 case '1':
 return '男';
 case '0':
 return '未知性别';
 case '9':
 return '未说明性别';
 default:
 return '未知';
 }
 })(Gender),
 pInfoDom = (
 <ul>
 <li>姓名：{Name}</li>
 <li>性别：{pGender}</li>
 <li>生日：{Birthday ? Birthday.format("YYYY-MM-DD") : ""}</li>
 <li>费别：{chargeType}</li>
 </ul>
 );
 return (
 <div>
 <div
 id="workspaceWrap"
 >
 <div
 id="_barTop"
 >
 <Title
 title={(
 <Popover
 content={pInfoDom}
 >
 <span>
 您正在书写
 <b
 style={{
 color: '#f00',
 fontWeight: 'normal',
 margin: '0 5px'
 }}
 >
 {Name}
 </b>
 的病例
 <Icon type="message"/>
 </span>
 </Popover>)}
 btnsRight={
 [<Button
 type="primary"
 key="btnPrint"
 onClick={this.onPrintPreview}
 >
 打印
 </Button>,
 <Button
 type="primary"
 key="btnView"
 >
 预览
 </Button>
 ]
 }
 btn2Text="保存"
 onState={this.need2save.bind(this, true)}
 />
 </div>
 <div
 id="_barWrap"
 >
 <div
 id="_barMain"
 >
 <ReportForm
 items={cates}
 types={types}
 cur={this.state.cur}
 forms={this.state.reportF}
 iHeight={this.state.iHeight}
 normalize={WriteReport.arr2ObjByKey}
 need2save={this.state.need2save}
 receiveData={this.receiveData.bind(this)}
 toolEvent={this.toolEvent.bind(this)}
 updateValue={this.updateValue.bind(this)}
 />
 <div
 id="_barLeft"
 >
 <CateBar
 items={cates}
 cur={this.state.cur}
 changeCate={this.changeCate.bind(this)}
 />
 </div>
 <div
 id="_barRight"
 >
 <TypeBar
 items={this.state.curCate}
 addType={this.addType.bind(this)}
 />
 </div>
 </div>
 </div>
 </div>
 <UploadImage
 {...this.state.addImgModal}
 onOk={this.addImgOnOk}
 onCancel={this.addImgOnCancel}
 />
 <div id="printWrapper"/>
 </div>
 );
 }
 }
 */
